package artid.com.arttogo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.iflytek.cloud.thirdparty.T;
import com.umeng.socialize.utils.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import artid.com.arttogo.R;
import artid.com.arttogo.adapter.AuctionSpecialInfo_Adapter;
import artid.com.arttogo.adapter.MainQuery_Adapter;
import artid.com.arttogo.adapter.ShootAdapter;
import artid.com.arttogo.bean.ArtList;
import artid.com.arttogo.bean.AuctionLotListParser;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.fragment.BaseFragment;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.view.xlistview.PLA_AbsListView;
import artid.com.arttogo.view.xlistview.PLA_AdapterView;
import artid.com.arttogo.view.xlistview.XListView;

/**
 * 类描述： 主页-查询页面
 * 创建人： 耿卫斌
 * 创建时间:2017/4/20 13:06
 */
public class MainQuery_Acivity extends BaseFragment  implements
        View.OnClickListener, XListView.IXListViewListener {
    private View v;
    private Context mContext;
    private RelativeLayout searchRL;
    private LinearLayout searchLL;
    private EditText searchEd;
    private TextView textsearch,searchCancelBtn;
    private ImageView searchIcon1,searchIcon2;
    private XListView mListView;
    private LinearLayout noDataLL;
    private TextView noDataHintTv;
    private boolean isRefreshed = false;// 是否刷新
    private int page = 1;
    private String imgwide;// 请求的图片宽度
    private int dataNum;//数据总条数
    private int requestDataNum=20;//请求数据数量
    private Boolean isLoad=true;//是否加载数据（默认可以加载）
    private MainQuery_Adapter mAdapter;
    private List<ArtList> list = new ArrayList<ArtList>();
    private List<ArtList> more_list = new ArrayList<ArtList>();
    private ArrayList<String> list_item;//点击事件传值使用
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.activity_mainquery, null);
        initView();
        return v;
    }

    private void initView(){
        mContext = getActivity();
        mBack = (ImageView) v.findViewById(R.id.back_btn);
        mBack.setVisibility(View.GONE);
        mTittle = (TextView) v.findViewById(R.id.tittle_text);
        mTittle.setText("查询");
        imgwide = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 2) + "";
        searchRL= (RelativeLayout) v.findViewById(R.id.MainQuery_searchRL);
        searchRL.setOnClickListener(this);
        searchLL= (LinearLayout) v.findViewById(R.id.MainQuery_searchLL);
        textsearch= (TextView) v.findViewById(R.id.MainQuery_textsearch);
        searchCancelBtn= (TextView) v.findViewById(R.id.MainQuery_searchCancelBtn);
        searchCancelBtn.setVisibility(View.GONE);
        searchCancelBtn.setOnClickListener(this);
        searchEd= (EditText) v.findViewById(R.id.MainQuery_searchEd);
        searchEd.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        searchEd.setVisibility(View.GONE);
        searchEd.setOnEditorActionListener(onEditor);
        searchIcon1 = (ImageView) v.findViewById(R.id.MainQuery_searchIcon1);
        searchIcon2 = (ImageView) v.findViewById(R.id.MainQuery_searchIcon2);
        searchIcon2.setVisibility(View.GONE);
        mListView= (XListView) v.findViewById(R.id.MainQuery_listView);
        mListView.setVisibility(View.GONE);
        mListView.setPullRefreshEnable(true);
        mListView.setPullLoadEnable(true);
        mListView.setXListViewListener(this);
        mListView.setOnScrollListener(onscrollListener);
        mListView.setOnItemClickListener(onItemClick);
        noDataLL = (LinearLayout) v.findViewById(R.id.ll_hint);
        noDataHintTv= (TextView) v.findViewById(R.id.ll_hint_tv);
        getData(true);
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        // 下拉刷新
        page = 1;
        isRefreshed = true;
        getData(true);
    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        // 上拉加载
        page++;
        getData(false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.MainQuery_searchRL:
                openKeyBoard();
                Animation scaleAnimation = new ScaleAnimation(1f, 0.8f, 1f, 1f, 1f, 1f);
                scaleAnimation.setDuration(400);
                scaleAnimation.setFillAfter(true);
                scaleAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation arg0) {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void onAnimationRepeat(Animation arg0) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onAnimationEnd(Animation arg0) {
                        // TODO Auto-generated method stub
                        searchIcon1.setVisibility(View.GONE);
                        textsearch.setVisibility(View.GONE);
                        searchIcon2.setVisibility(View.VISIBLE);
                        searchEd.setVisibility(View.VISIBLE);
                        searchCancelBtn.setVisibility(View.VISIBLE);
                        searchEd.setFocusable(true);
                        searchEd.setFocusableInTouchMode(true);
                        searchEd.requestFocus();
                    }
                });
                searchLL.setAnimation(scaleAnimation);
                break;
            case R.id.MainQuery_searchCancelBtn:
                closeKeyBoard();
                Animation scaleAnimation2 = new ScaleAnimation(0.8f, 1f, 1f, 1f, 1f, 1f);
                scaleAnimation2.setDuration(500);
                scaleAnimation2.setFillAfter(true);
                searchLL.setAnimation(scaleAnimation2);
                searchIcon2.setVisibility(View.GONE);
                searchCancelBtn.setVisibility(View.GONE);
                searchEd.setVisibility(View.GONE);
                searchEd.setText("");
                textsearch.setVisibility(View.VISIBLE);
                searchIcon1.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * item点击事件
     */
    PLA_AdapterView.OnItemClickListener onItemClick=new PLA_AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(PLA_AdapterView<?> parent, View view,int Position, long id) {
            int position = Position - 1;
            if (position >= 0) {
                Intent intent = new Intent(getActivity(), CollectionDetailPagerActivity.class);
                intent.putStringArrayListExtra("id", list_item);
                intent.putExtra("index", position);
                if(list.get(position).getIs_type()==2) {
                    //机构
                    intent.putExtra("isOrg", true);
                }else{
                    //艺术家
                    intent.putExtra("isOrg", false);
                }
                startActivity(intent);
            }
        }
    };

    /**
     * 请求数据
     * @param isLoadDialog 是否显示加载
     * 艺术品页码	page
        关键字	keyword
        艺术品行数	pagesize
        鉴证状态	status	全部作品：0，审核中：1，已备案： 2
        图片宽	width
     */
    private void getData(Boolean isLoadDialog){
        final String keyword=searchEd.getText().toString();
        isLoad=false;
        if(isLoadDialog){
            VolleyBasic.showLoding(mContext);
        }
        VolleyBasic.getInstanceNoDialog(getActivity()).post(
                Cache.allArtList,
                VolleyMap.getInstance().selectArt(keyword,"2",imgwide,page,requestDataNum),
                ArtList.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        isLoad=true;
                        if (isRefreshed) {
                            mListView.stopRefresh();
                        } else {
                            mListView.stopLoadMore();
                        }
                        list = (List<ArtList>) vd.getList();
                        if(page==1) {
                            try {
                                JSONObject jsonObject = new JSONObject(vd.getJson());
                                dataNum = jsonObject.getInt("num");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        if (isRefreshed == true) {
                            more_list.clear();
                            isRefreshed = false;
                        }
                        if (!list.isEmpty()) {
                            more_list.addAll(list);
                        }
                        if (mAdapter == null) {
                            mAdapter = new MainQuery_Adapter(mContext, more_list);
                            mListView.setAdapter(mAdapter);

                        }
                        mAdapter.notifyDataSetChanged();
                        if(more_list==null || more_list.size()==0) {
                            if (!TextUtils.isEmpty(keyword)) {
                                noDataHintTv.setText("暂无您查询的数据");
                            } else {
                                noDataHintTv.setText("目前还没有相关内容");
                            }
                            //这里因为要搜索可能会空所有的刷新Adapter
                            mAdapter = new MainQuery_Adapter(mContext, more_list);
                            mListView.setAdapter(mAdapter);
                            noDataLL.setVisibility(View.VISIBLE);
                        }else{
                            list_item = new ArrayList<String>();
                            for (int i = 0; i < more_list.size(); i++) {
                                list_item.add(more_list.get(i).getArt_id());
                            }
                            mListView.setVisibility(View.VISIBLE);
                        }
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        isLoad=true;
                        if(more_list==null || more_list.size()==0) {
                            if (!TextUtils.isEmpty(keyword)) {
                                noDataHintTv.setText("暂无您查询的数据");
                            } else {
                                noDataHintTv.setText("目前还没有相关内容");
                            }
                            noDataLL.setVisibility(View.VISIBLE);
                        }else{
                            {
                                mListView.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                });
    }

    /**
     * 瀑布流滑动事件
     */
    PLA_AbsListView.OnScrollListener onscrollListener=new PLA_AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(PLA_AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
           if(more_list.size()!=dataNum && isLoad==true){
                //-11是数据已经显示一半的时候如果加头了就-12
                if(page==1 && firstVisibleItem==(requestDataNum-11)){
                    page++;
                    getData(false);
                }else if(((page*requestDataNum)-11)==firstVisibleItem){
                    page++;
                    getData(false);
                }
            }
        }
    };

    //软键盘回车键修改
    TextView.OnEditorActionListener onEditor=new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                //执行搜索事件
                page = 1;
                isRefreshed = true;
                getData(true);
                return true;
            }
            return false;
        }
    };


    /**
     * 开启软键盘
     */
    private void openKeyBoard() {
        InputMethodManager m = (InputMethodManager) searchEd.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 关闭软键盘
     */
    private void closeKeyBoard() {
        try {
            InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
            // TODO: handle exception
            Log.d("", "关闭输入法异常");
        }
    }

}
